package com.zookeeper.case1;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @author WangGuoLiang
 * @program ZooKeeper
 * @description 模拟服务器向ZooKeeper注册
 * @create 2021-09-05 00:26
 **/
public class DistributeServer {
    ZooKeeper zooKeeper;
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        DistributeServer distributeServer = new DistributeServer();
        //1 连接zookeeper
        distributeServer.getZk();
        //2 注册到zookeeper
        distributeServer.regist("host1");
        //3 启动业务类 ---主线程休眠
        distributeServer.business();

    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String hostname) throws KeeperException, InterruptedException {
        zooKeeper.create("/servers/"+hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname +"上线");
    }

    private void getZk() throws IOException {
         zooKeeper = new ZooKeeper("47.106.199.16:2181", 2000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });

    }
}

